﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Bowerbird.Core.Storage
{
    public static class RepositoryBase<T>
        where T: class
    {

        public static T GetById(string id)
        {
            T obj = default(T);
            IList exp = new ArrayList();

            exp.Add(NHibernate.Criterion.Expression.Eq("Id", id));
            
            IList<T> list = NHibernateManager.GetObjectList<T>(exp);
            
            if (list.Count == 1)
                obj = list[0];
            else if (list.Count > 1)
                throw new Exception("Unexpected entity count exception. Only one entity was expected.");

            return obj;
        }

        public static IList<T> GetAll()
        {
            return NHibernateManager.GetObjectList<T>();
        }

        public static T SaveOrUpdate(T entity)
        {
            NHibernateManager.SaveOrUpdateObject(entity);
            NHibernateManager.NHSession.Refresh(entity);
            return entity;
        }

        public static void Delete(T entity)
        {
            NHibernateManager.DeleteObject(entity);
        }

    }
}
